package cn.edu.zjusc.Servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AvatarServlet
 */
public class AvatarServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AvatarServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	private byte[] FlashDataDecode(String s) {
		byte[] r = new byte[s.length() / 2];
		int l = s.length();
		for (int i = 0; i < l; i = i + 2) {
			int k1 = (s.charAt(i)) - 48;
			k1 -= k1 > 9 ? 7 : 0;
			int k2 = (s.charAt(i + 1)) - 48;
			k2 -= k2 > 9 ? 7 : 0;
			r[i / 2] = (byte) (k1 << 4 | k2);
		}
		return r;
	}

	private boolean SaveAvatar(String avatarData, String uid) {
		String dirPath = getServletConfig().getServletContext().getRealPath(
				"/userfiles/image/");

		byte[] b = FlashDataDecode(avatarData);
		if (b.length == 0)
			return false;
		String avatarFileName = String.format("%s\\%s.jpg", dirPath, uid);
		System.out.println(avatarFileName);
		try {
			File file = new File(avatarFileName);
			if (!file.exists()) {
				file.createNewFile();
			}

			FileOutputStream fos = new FileOutputStream(file);
			fos.write(b);
			fos.flush();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		String uid = request.getParameter("input");
		String avatarData = request.getParameter("avatar1");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		if (SaveAvatar(avatarData, uid)) {
			out.print("<?xml version=\"1.0\" ?><root><face success=\"1\"/></root>");
		} else {
			out.print("<?xml version=\"1.0\" ?><root><face success=\"0\"/></root>");
		}
		out.flush();
		out.close();
		return;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(request, response);
	}

}
